module(..., package.seeall)

require "aLiOutMsg"
require "tool"
require "misc"
-- require "-- mqttOutMsg"
require "aLiOTA"
require "httpsGet"
require "lbsLoc"
require "aLiIotda"

local cpu_temp = 0
local lng_value = "0"
local lat_value = "0"
local beat = 0
local history_post = false
local temp_list = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}

-- 获取CPU温度回调函数
local function getTemperatureCb(temp)
    cpu_temp = temp
    log.info("CPU_TEMP", cpu_temp)
end

-- 获取网关的经纬度
local function getLocCb(result, lat, lng, addr, time, locType)
    log.info("testLbsLoc.getLocCb", result, lat, lng)
    -- 获取经纬度成功
    if result == 0 then
        -- log.info("服务器返回的时间", time:toHex())
        -- log.info("定位类型，基站定位成功返回0", locType)
        lat_value = tostring(lat)
        lng_value = tostring(lng)
        return true
        -- 失败
    else
        return false
    end
end

-- 设备初次启动
function onceStart()
    if aLiIotda.isReady() then
        sys.taskInit(function()
            ril.regUrc("+NITZ", function()
                log.info("cell.timeSync")
                bTimeSyned = true
            end)

            if history_post == false then
                -- historyPost()
                sys.wait(1000)
                lbsLoc.request(getLocCb)
                local t = misc.getClock()
                misc.getTemperature(getTemperatureCb)

                sys.wait(1000)
                -- local num, on_num = ui_index.returnOnlineNum()
                local re = {}

                re["id"] = tool.miscTime()
                re["params"] = {}
                re["params"]["rssiValue"] = net.getRssi() -- 4G信号强度
                re["params"]["deviceName"] = "GWEV_" .. misc.getImei() -- 模块IMEI
                re["params"]["iccidValue"] = sim.getIccid() -- 4G物联网卡ICCID
                re["params"]["powerOnTime"] = tool.miscTime() .. "000" -- 开机时间
                re["params"]["liveTime"] = tool.miscTime() .. "000" -- 心跳时间
                re["params"]["cpuTemp"] = cpu_temp -- cpu温度
                re["params"]["type"] = "485_GW"
                re["params"]["devModel"] = nvm.get("DEV_TYPE")
                re["params"]["devType"] = tool.getDevType()
                re["params"]["baudRate"] = nvm.get("DEV_BAUD")
                re["params"]["powerVol"] = tonumber(misc.getVbatt())

                if nvm.get("DEV_TYPE") ~= "NONE" then
                    re["params"]["address"] = nvm.get("DEV_ADDR")
                end

                if lat_value ~= "0" or lng_value ~= "0" then
                    re["params"]["latValue"] = lat_value -- 纬度
                    re["params"]["lngValue"] = lng_value -- 经度
                end
                -- re["params"]["devBindedNum"] = num
                -- re["params"]["devOnlineNum"] = on_num

                re["version"] = "1.0"
                re["method"] = "thing.event.property.post"
                log.info("ALI_TOPIC",
                         "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                             misc.getImei() .. "/thing/event/property/post")

                -- 上传网关物模型信息，非每次自动重启的时间点才上传
                if t["hour"] ~= 22 and t["min"] ~= 30 then
                    aLiOutMsg.aLiInstertMsg(
                        "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                            misc.getImei() .. "/thing/event/property/post", re)
                end

                eventPost("PhaseLoss")

                -- -- mqttOutMsg.mqttInsertMsg(config.MQTT_TOPIC2, re)
            end
        end)
    end
end

-- 心跳包
local function heartbeat()
    if aLiIotda.isReady() then
        sys.taskInit(function()
            lbsLoc.request(getLocCb)
            misc.getTemperature(getTemperatureCb)

            if history_post == false then
                -- 先发送缓存的数据
                -- historyPost()
                -- local num, on_num = ui_index.returnOnlineNum()
                local re = {}
                sys.wait(1000)
                re["id"] = tool.miscTime()
                re["params"] = {}
                re["params"]["rssiValue"] = net.getRssi()
                re["params"]["deviceName"] = "GWEV_" .. misc.getImei()
                re["params"]["iccidValue"] = sim.getIccid()
                re["params"]["liveTime"] = tool.miscTime() .. "000"
                re["params"]["cpuTemp"] = cpu_temp
                re["params"]["type"] = "485_GW"
                re["params"]["devModel"] = nvm.get("DEV_TYPE")
                re["params"]["devType"] = tool.getDevType()
                re["params"]["baudRate"] = nvm.get("DEV_BAUD")
                re["params"]["powerVol"] = tonumber(misc.getVbatt())
                if lat_value ~= "0" or lng_value ~= "0" then
                    re["params"]["latValue"] = lat_value -- 纬度
                    re["params"]["lngValue"] = lng_value -- 经度
                end

                if nvm.get("DEV_TYPE") ~= "NONE" then
                    re["params"]["address"] = nvm.get("DEV_ADDR")
                end

                re["version"] = "1.0"
                re["method"] = "thing.event.property.post"

                log.info("ALI_TOPIC",
                         "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                             misc.getImei() .. "/thing/event/property/post")
                aLiOutMsg.aLiInstertMsg(
                    "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                        misc.getImei() .. "/thing/event/property/post", re)
                -- -- mqttOutMsg.mqttInsertMsg(config.MQTT_TOPIC2, re)
            end
        end)
    end
end

-- 数据上传
function dataPost(data, dataHex)
    if aLiIotda.isReady() then
        beat = tool.miscTime()
        sys.taskInit(function()

            if history_post == false then
                -- 先发送缓存的数据
                -- historyPost()

                lbsLoc.request(getLocCb)
                misc.getTemperature(getTemperatureCb)

                local re = {}
                sys.wait(1000)
                re["id"] = tool.miscTime()
                re["params"] = {}
                re["params"]["rssiValue"] = net.getRssi()
                re["params"]["deviceName"] = "GWEV_" .. misc.getImei()
                re["params"]["iccidValue"] = sim.getIccid()
                re["params"]["liveTime"] = tool.miscTime() .. "000"
                re["params"]["cpuTemp"] = cpu_temp
                re["params"]["type"] = "485_GW"
                re["params"]["dataString"] = data
                re["params"]["dataHex"] = dataHex
                re["params"]["devModel"] = nvm.get("DEV_TYPE")
                re["params"]["devType"] = tool.getDevType()
                re["params"]["baudRate"] = nvm.get("DEV_BAUD")
                re["params"]["powerVol"] = tonumber(misc.getVbatt())
                if lat_value ~= "0" or lng_value ~= "0" then
                    re["params"]["latValue"] = lat_value -- 纬度
                    re["params"]["lngValue"] = lng_value -- 经度
                end

                if nvm.get("DEV_TYPE") ~= "NONE" then
                    re["params"]["address"] = nvm.get("DEV_ADDR")
                end

                re["version"] = "1.0"
                re["method"] = "thing.event.property.post"

                log.info("ALI_TOPIC",
                         "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                             misc.getImei() .. "/thing/event/property/post")
                aLiOutMsg.aLiInstertMsg(
                    "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                        misc.getImei() .. "/thing/event/property/post", re)
                -- -- mqttOutMsg.mqttInsertMsg(config.MQTT_TOPIC2, re)
            end
        end)
    end
end

-- 断电推送
function poweroff()
    if aLiIotda.isReady() then
        sys.taskInit(function()
            lbsLoc.request(getLocCb)
            misc.getTemperature(getTemperatureCb)

            -- local num, on_num = ui_index.returnOnlineNum()
            local re = {}
            sys.wait(1000)
            re["id"] = tool.miscTime()
            re["params"] = {}
            re["params"]["rssiValue"] = net.getRssi()
            re["params"]["deviceName"] = "GWEV_" .. misc.getImei()
            re["params"]["iccidValue"] = sim.getIccid()
            re["params"]["powerOffTime"] = tool.miscTime() .. "000"
            re["params"]["cpuTemp"] = cpu_temp
            if lat_value ~= "0" or lng_value ~= "0" then
                re["params"]["latValue"] = lat_value -- 纬度
                re["params"]["lngValue"] = lng_value -- 经度
            end
            -- re["params"]["devBindedNum"] = num
            -- re["params"]["devOnlineNum"] = on_num
            re["version"] = "1.0"
            re["method"] = "thing.event.property.post"

            log.info("ALI_TOPIC",
                     "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                         misc.getImei() .. "/thing/event/property/post")
            aLiOutMsg.aLiInstertMsg("/sys/" .. config.ALI_PRODUCTKEY .. "/" ..
                                        "GWEV_" .. misc.getImei() ..
                                        "/thing/event/property/post", re)
            -- mqttOutMsg.mqttInsertMsg(config.MQTT_TOPIC2, re)
        end)
    end

end

-- 收到订阅的Topic，网关的处理函数
function aLiMqttCMD(topic, payload)
    local res = tool.Split(topic, "/")
    local jsondata, json_result, errinfo = json.decode(payload)
    if res[4] == "upgrade" then
        aLiOTA.upgrade(payload)
    elseif res[5] == "rrpc" then
        log.info("RRPC", "get RRPC CMD")
        if json_result then
            log.info("CMDDATA", jsondata["params"]["cmdData"])
            cmd_res = tool.Split(jsondata["params"]["cmdData"], ',')
            if cmd_res[1] == "CMDHEX" and #cmd_res == 2 then
                deviceConfig.mqttSend(cmd_res[2], topic, "L")
            elseif cmd_res[1] == "CMDBAUD" and #cmd_res == 2 then
                deviceConfig.set485_baud(cmd_res[2], topic, "L")
            elseif cmd_res[1] == "CMDADDR" and #cmd_res == 2 then
                deviceConfig.set485_addr(cmd_res[2], topic, "L")
            elseif cmd_res[1] == "CMDTYPE" and #cmd_res == 2 then
                deviceConfig.set485_type(cmd_res[2], topic, "L")
            elseif cmd_res[1] == "CMDEVEN" and #cmd_res == 2 then
                deviceConfig.set485_even(cmd_res[2], topic, "L")
            elseif cmd_res[1] == "CMDTIME" and #cmd_res == 2 then
                deviceConfig.set485_time(cmd_res[2], topic, "L")
            end

            deviceConfig.testDevice(0)
        end

    end
end

function eventPost(str)
    local topic = "/sys/" .. config.ALI_PRODUCTKEY .. "/" .. "GWEV_" ..
                      misc.getImei() .. "/thing/event/gatewayEvent/post"
    local re = {}
    re["id"] = tostring(tool.miscTime())
    re["version"] = "1.0"
    re["params"] = {}
    re["params"]["value"] = {}
    re["params"]["value"]["eventData"] = str
    re["method"] = "thing.event.gatewayEvent.post"
    aLiOutMsg.aLiInstertMsg(topic, re)
end

sys.taskInit(function()
    local result, data = sys.waitUntil("ALI_MQTT_READY", 300000)
    log.info("TIME STAMP:", tool.miscTime())
    if result then
        sys.wait(6000)
        onceStart()
        -- 发送缓存中的数据
        -- historyPost()

        while true do
            sys.wait(300000)
            if tool.miscTime() - beat > 300 then heartbeat() end
        end
    end
end)
